package com.example.traning.web.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @author lei yu
 * @since 2025/04/27
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception e) {
        log.info("全局异常处理");

        if (e instanceof BizException) {
            BizException ex = (BizException) e;
            return R.err(String.format("业务异常：%s", ex.getMessage()));
        }

        // 处理 SpringMVC 参数校验不正确
        if (e instanceof MethodArgumentNotValidException ex) {
            String errorMessage = ex.getBindingResult().getAllErrors().getFirst().getDefaultMessage();
            return R.err(String.format("请求参数不正确：%s", errorMessage));
        }

        log.info("[兜底异常] msg: {}, 打印堆栈\n{}", e.getMessage(), e.getStackTrace());
        return R.err(e.getMessage());
    }
}
